package com.example.demo.controller;

import com.example.demo.model.dto.TaskDTO;
import com.example.demo.service.ProcessService;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/process")
public class ProcessController {

    @Autowired
    private ProcessService processService;

    /**
     * 启动请假申请流程
     */
    @PostMapping("/leave-request")
    public ResponseEntity<Map<String, String>> startLeaveRequest(
            @RequestParam String employee,
            @RequestParam String reason,
            @RequestParam int days) {
        
        String processInstanceId = processService.startLeaveRequest(employee, reason, days);
        
        Map<String, String> response = new HashMap<>();
        response.put("processInstanceId", processInstanceId);
        response.put("message", "请假申请流程已启动");
        
        return ResponseEntity.ok(response);
    }

    /**
     * 获取用户的任务列表
     */
    @GetMapping("/tasks/user/{assignee}")
    public ResponseEntity<List<TaskDTO>> getUserTasks(@PathVariable("assignee") String assignee) {
        List<Task> tasks = processService.getUserTasks(assignee);


        TaskDTO taskDTO = new TaskDTO();
        List<TaskDTO> list = tasks.stream().filter(Objects::nonNull)
                .map(taskDTO::convert)
               .collect(Collectors.toList());
        return ResponseEntity.ok(list);
    }



    /**
     * 获取候选组的任务列表
     */
    @GetMapping("/tasks/group/{group}")
    public ResponseEntity<List<Task>> getGroupTasks(@PathVariable("group") String group) {
        List<Task> tasks = processService.getGroupTasks(group);
        return ResponseEntity.ok(tasks);
    }

    /**
     * 完成任务
     */
    @PostMapping("/tasks/{taskId}/complete")
    public ResponseEntity<Map<String, String>> completeTask(
            @PathVariable("taskId") String taskId,
            @RequestBody Map<String, Object> variables) {
        
        processService.completeTask(taskId, variables);
        
        Map<String, String> response = new HashMap<>();
        response.put("message", "任务已完成");
        
        return ResponseEntity.ok(response);
    }

    /**
     * 获取任务详情
     */
    @GetMapping("/tasks/{taskId}")
    public ResponseEntity<Task> getTask(@PathVariable("taskId") String taskId) {
        Task task = processService.getTask(taskId);

        TaskDTO taskDTO = new TaskDTO();
        taskDTO.convert(task);
        return ResponseEntity.ok(task);
    }
} 